package com.hns.can.master.service;

import java.math.BigDecimal;
import java.security.PublicKey;
import java.util.*;

import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.formula.FillParamsVo;
import com.hns.can.master.entity.BaseCarInfoEntity;
import com.hns.can.master.entity.BaseLineInfoEntity;
import com.hns.can.master.entity.BaseStnInfoEntity;
import com.hns.can.master.vo.StnPostDataVo;
import com.hns.frame.enumrate.EnabledSt;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilString;
import com.itextpdf.text.log.SysoCounter;

/**
 * 站点信息维护业务类
 * @author:lan
 * @email:763836737@qq.com
 * @version Revision 2.0.0
 */
@Service
public class StationInfoService extends CommonService {
    
	/**
	 * 填充代码描述
	 */
    @Autowired
    private FillCodeDscValue codeDscValue;
    
    /**
     * 添加一个站点
     * @param entity
     * @param user
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public void addStationInfo(BaseStnInfoEntity entity, SysUserEntity user) {
        // 补充实体的其他信息
        if("".equals(entity.getCorpId())){
            entity.setCorpId(user.getCorpId());
        }
        entity.setStnId(UtilString.getUUID());
        entity.setEnabledSt(EnabledSt.ENABLE.getFlag());  // 启用状态
        entity.setCrtTime(new Date());
        entity.setCrtUser(user.getAcctName());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        // 做后台校验
        // -- 站点编号不能重复
        this.check("stationInfo.checkStnCd", entity, "您输入的站点编号已经存在！");
        commonEntityDao.save(entity);
    }
    
    /**
     * 得到站点page对象
     * @param dataVo
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public Pagination searchStationInfoPage(StnPostDataVo dataVo,SysUserEntity user) {
        if("".equals(dataVo.getCorpId())){
            dataVo.setCorpId(user.getCorpId());
        }
        Pagination page = this.myBatisPage("stationInfo.getStationInfoCnt","stationInfo.getStationInfoList",dataVo,BaseStnInfoEntity.class);
        return page;
    }
    
    /**
     * 得到站点信息list对象
     * @param dataVo
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    @Transactional
    public List<BaseEntity> getStationInfoList(StnPostDataVo dataVo) {
        List<BaseEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("stationInfo.getStationInfoList", dataVo), BaseStnInfoEntity.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("direction","LIT00000");
        codeDscValue.fillCodeDscValue(list,map);
        return list;
    }
    
   /**
    * 根据站点id求站点信息
    * @param stnId
    * @return
    * @throws Exception
    * @author:lan
    * @email:763836737@qq.com
    */
    @Transactional
    public BaseStnInfoEntity getStationInfoByStnId(String stnId) throws Exception {
        BaseStnInfoEntity entity = commonEntityDao.find(stnId, BaseStnInfoEntity.class);
        List<BaseEntity> list = new ArrayList<BaseEntity>();
        list.add(entity);
        Map<String,String> map = new HashMap<String,String>();
        map.put("corpName", GlobalConst.DEFAULT_CACHE_VALUE);   
        FillParamsVo vo = new FillParamsVo("corpId", map);
        codeDscValue.fillInfoValue(list, new String[]{GlobalConst.CACHE_KEY_SYS_CORP}, vo);
        return entity;
    }
    
    /**
     * 更新一个站点的信息
     * @param user
     * @param entity
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public void uptStationInfo(SysUserEntity user, BaseStnInfoEntity entity){
        BaseStnInfoEntity tmpEntity = commonEntityDao.find(entity.getStnId(), BaseStnInfoEntity.class);
        entity.setEnabledSt(tmpEntity.getEnabledSt());  // 启用状态
        entity.setCrtTime(tmpEntity.getCrtTime());
        entity.setCrtUser(tmpEntity.getCrtUser());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        
        // 做后台校验
        // -- 站点编号不能重复，除了自身之外
        this.check("stationInfo.checkStnCd", entity, "您输入的站点编号已经存在！");
        commonEntityDao.update(entity);
    }
    
    /**
     * 删除一个站点
     * @param user
     * @param stnIds
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public void delStationInfo(SysUserEntity user, String[] stnIds){
        for (String stnId : stnIds) {
            BaseStnInfoEntity entity = commonEntityDao.find(stnId, BaseStnInfoEntity.class);
            entity.setEnabledSt(EnabledSt.DISABLE.getFlag());
            entity.setUpdateTime(new Date());
            entity.setUpdateUser(user.getAcctName());
            // 删除的验证操作
            /*如果站点已经绑定在线路上，就不能被删除。提醒从线路上解除绑定，再进行删除。*/
            this.check("stationInfo.checkStnInLine", entity, "该站点已经绑定在线路上，请解除绑定再进行删除！");
            commonEntityDao.update(entity);
        }
    }

    /**
     * 获取公司下所有启用线路信息
     * @param entity
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    @Transactional
    public List<BaseLineInfoEntity> getBaseLineInfoList(BaseLineInfoEntity entity) {
        List<BaseLineInfoEntity> list = PubUtil.convertListMapToObject(
            this.sqlMapDao.selectList("stationInfo.getBaseLineInfoList", entity), BaseLineInfoEntity.class);
        return list;
    }

    /**
     * 获得线路下的所有站点
     * @param paraMap
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings({"unchecked"})
    @Transactional
    public List<BaseEntity> getStationInfoListByLineId(Map<String, Object> paraMap) throws Exception {
        List<BaseEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("stationInfo.getStationInfoListByLineId", paraMap), BaseStnInfoEntity.class);
        Map<String,String> map2 = new HashMap<String,String>();
        map2.put("lineName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("lineId", map2);
        codeDscValue.fillInfoValue(list, new String[] {GlobalConst.CACHE_KEY_BASE_LINE_INFO}, vo2);
        Map<String,String> mapTmp = new HashMap<String,String>();
        mapTmp.put("lineType", "LIT00000");
//        mapTmp.put("lineId", "LIN00000");
        codeDscValue.fillCodeDscValue(list, mapTmp);
        return list;
    }

    /**
     * 更新对应站点的经纬度
     * @param list
     * @param user
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public String saveToDB(List<BaseStnInfoEntity> list, SysUserEntity user,String corpId) {
        String msgs = "";
        String allMsg= "";
        String enabledSt = "1";
        String stnCd = "";
        BigDecimal lgt = null;
        BigDecimal ltt = null;
        int i = 1;
        successCount = 0;
        for(BaseStnInfoEntity tmpEntity:list){
            i++;
            msgs = "";
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("corpId",corpId);
            map.put("stnCd",tmpEntity.getStnCd());
//            map.put("direction",tmpEntity.getDirection());
            map.put("enabledSt","1");
            if(PubUtil.isEmpty(tmpEntity.getStnCd())){
                msgs = "";
                msgs = "<span>·</span>站点编号不能为空，第"+i+"行的站点编号为空。<br/> ";
                allMsg = allMsg + msgs;
                continue;
            }else if(PubUtil.isEmpty(tmpEntity.getStnName())){
                msgs = "";
                msgs = "<span>·</span>站点名称不能为空，第"+i+"行的站点名称为空。<br/> ";
                allMsg = allMsg + msgs;
                continue;
            }
            List<BaseStnInfoEntity> stnInfo = commonEntityDao.findByParamsIgnoreNullValue(BaseStnInfoEntity.class, map);
            if(stnInfo.size() > 0){
                BaseStnInfoEntity entity = stnInfo.get(0);
                entity.setStnName(tmpEntity.getStnName());
                entity.setStnAlias(tmpEntity.getStnAlias());
                if(PubUtil.isNotEmpty(tmpEntity.getLgt())){
                    lgt = new BigDecimal(lgtLtt(tmpEntity.getLgt()));
                    entity.setLgt(lgt);
                }else{
                    entity.setLgt(null);
                }
                if(PubUtil.isNotEmpty(tmpEntity.getLtt())){
                    ltt = new BigDecimal(lgtLtt(tmpEntity.getLtt()));
                    entity.setLtt(ltt);
                }else{
                    entity.setLtt(null);
                }
                entity.setLoDetailInfo(tmpEntity.getLoDetailInfo());
                entity.setRemark(tmpEntity.getRemark());
                entity.setDirection(tmpEntity.getDirection());
                entity.setEnabledSt(EnabledSt.ENABLE.getFlag());
                entity.setUpdateTime(new Date());
                entity.setUpdateUser(user.getAcctName());
                entity.setOutRadius(tmpEntity.getOutRadius());
                entity.setInRadius(tmpEntity.getInRadius());
                entity.setSpeedLimit(tmpEntity.getSpeedLimit());
                entity.setRoad(tmpEntity.getRoad());
                commonEntityDao.update(entity);
            }else{
                tmpEntity.setStnId(UtilString.getUUID());
                tmpEntity.setCorpId(corpId);
                tmpEntity.setEnabledSt(EnabledSt.ENABLE.getFlag());
                tmpEntity.setCrtUser(user.getAcctName());
                tmpEntity.setCrtTime(new Date());
                commonEntityDao.save(tmpEntity);
            }
            successCount++;
            allMsg = allMsg + msgs;
//        	 i++;
//            Map<String, Object> map2 = new HashMap<String, Object>();
//            map2.put("lineName", tmpEntity.getLineName());
//            map2.put("corpId", corpId);
//            List<BaseLineInfoEntity> lineInfo = commonEntityDao.findByParamsIgnoreNullValue(BaseLineInfoEntity.class, map2);
//                if(lineInfo.size() >= 1){
//                    Map<String, Object> map = new HashMap<String, Object>();
//                    map.put("corpId",corpId);
//                    map.put("stnCd",tmpEntity.getStnCd());
//                    map.put("enabledSt", enabledSt);
//                    List<BaseStnInfoEntity> stnList = commonEntityDao.findByParamsIgnoreNullValue(BaseStnInfoEntity.class, map);
//                    if(PubUtil.isNotEmpty(stnList)){
//                    	BaseStnInfoEntity entity = stnList.get(0);
//                    	entity.setStnName(tmpEntity.getStnName());
//                    	entity.setStnAlias(tmpEntity.getStnAlias());
//                    	entity.setLgt(tmpEntity.getLgt());
//                        entity.setLtt(tmpEntity.getLtt());
//                        entity.setUpdateTime(new Date());
//                        entity.setUpdateUser(user.getAcctName());
//                    	commonEntityDao.update(entity);
//                    }else{
//                    	BaseStnInfoEntity entity = new BaseStnInfoEntity();
//                    	entity.setLgt(tmpEntity.getLgt());
//                        entity.setLtt(tmpEntity.getLtt());
//                    	entity.setStnId(UtilString.getUUID());
//                        entity.setStnAlias(tmpEntity.getStnAlias());
//                        entity.setEnabledSt(EnabledSt.ENABLE.getFlag());  // 启用状态
//                        entity.setCrtTime(new Date());
//                        entity.setCrtUser(user.getAcctName());
//                        entity.setUpdateTime(new Date());
//                        entity.setUpdateUser(user.getAcctName());
//                        entity.setCorpId(corpId);
//                        entity.setStnCd(tmpEntity.getStnCd());
//                        entity.setStnName(tmpEntity.getStnName());
//                        commonEntityDao.save(entity);
//                    }
//                }else if(!"".equals(tmpEntity.getLineName())){
//                    throw new BusinessException(MsgType.WARN.getFlag(),"第"+(i+1)+"行的"+tmpEntity.getLineName()+"线路不存在");
//                }
            }
            return allMsg;
//        if(msgs.length() > 13){
//             throw new BusinessException(MsgType.WARN.getFlag(),msgs);
//        }
    }
    //判断是否是经纬度格式
//    public static boolean isNum(String cellValue){
//        if(cellValue.indexOf(".") == -1){
//            return false;
//        }
//        String a = cellValue.substring(cellValue.indexOf(".")+1,cellValue.length());
//        if(a.length()!=6){
//            return false;
//        }
//        return true;
//    }

    //转化经纬度格式
    public static String lgtLtt(BigDecimal cellValue){
        String value = cellValue.toString();
        if(value.indexOf(".") == -1){
            return value+".000000";
        }
        String[] values = value.split("\\.");
        String value1 = values[0];
        String value2 = values[1];
        if(value2.length() > 6){
            value2 = value2.substring(0,6);
        }
        return value1+"."+value2;
    }
    private  int successCount;

    public int getSuccessCount() {
        return successCount;
    }


}
